# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from DBUtils.PooledDB import PooledDB

import pymysql
import re
class xxPipeline:
    def __init__(self):
        config = {
            'host': '127.0.0.1',
            'port': 3306,
            'database': 'dht',
            'user': 'root',
            'password': '123456',
            'charset': 'utf8'
        }
        self.pool = PooledDB(creator=pymysql, mincached=2, maxcached=40, maxconnections=50, **config)

    def process_item(self, item, spider):


        conn = self.pool.connection()
        cur = conn.cursor()  # 创建游标，增删改查都在游标上进行
        #print(dhtInfo)
        sql = "insert into bt(infohash,length,time,lasttime,name)values(%s,%s,%s,%s,%s)"
        data = []
       # print(dhtInfo)
       # print(dhtInfo['magnet'])
       # print(utils.Utils.formatMagnet(dhtInfo['magnet']))
        magnet2 = re.findall(r'xt=urn:btih:\w*', item['magnet'])
        data.append(magnet2[0].split(':')[2])

        leng = len(item['size'].strip())
        unit = item['size'].strip()[-1:]
        if unit.upper() == 'G' or unit.upper() == 'M' or unit.upper() == 'K':
            len1 = 1
        else:
            unit = item['size'][-2:]
            if unit.upper() == 'ES':
                len1 = 5
            else:
                len1 = 2

        byte = item['size'].strip()[0:leng - len1].strip()
        dataByte = {'MB': 1024 * 1024, 'GB': 1024 * 1024 * 1024, 'KB': 1024, 'ES': 1, 'G': 1024 * 1024 * 1024,'M': 1024 * 1024, 'K': 1024}
        data.append(int(float(byte) * float(dataByte[unit.upper()])))
        data.append(item['time'])
        data.append(item['time'])
        data.append(item['title'])
        # data.append(item['files'])
        print(data)
        cur.execute(sql, data)
        conn.commit()
        cur.close()
        conn.close()


        return item

